/* 公共js方法 */
/*
-1 后台异常
-2 管理员已经登录，无法再次登录
-3 心跳成功
-5 心跳失败
-4 没有登录
*/
define([
    'toastr',
], function(toastr) {
    'use strict';

    var heartbeatCount = null;

    toastr.options = {
        positionClass: "toast-bottom-right"
    }

    $('#loginOut').click(function() {
        common.loginOut();
    });
    var common = {
        debug: false,
        // ip: 'http://localhost:5757/weapp/', // 本地环境
        // src: 'http://localhost:5757/',
        ip: window.ip + '/weapp/', // 开发环境
        src: window.ip + '/',
        // ip: 'https://120473951.yqvhk.club/weapp/', // 生产环境
        // src: 'http://localhost:5757/',
        animationType: 'rotate,rotateX,rotateY,rotateZ,rotate3d,scale,scaleX,scaleY,scaleZ,scale3d,translate,translateX,translateY,translateZ,translate3d,skew,skewX,skewY,matrix,matrix3d',
        ajax: function(url, param, async_, type, timeout) {
            var self = this;
            return $.ajax({
                url: self.ip + url + '?' + localStorage.loginUid,
                data: param,
                type: type || 'POST',
                async: async_,
                timeout: timeout || 60000
            });
        },
        fileAjax: function(url, param, async_, timeout) {
            var self = this;
            return $.ajax({
                url: self.ip + url + '?' + localStorage.loginUid,
                data: param,
                type: 'POST',
                async: async_,
                timeout: timeout || 1000000000,
                contentType: false,
                processData: false,
                cache: false
            });
        },
        getUrl: function(action) {
            return this.ip + action;
        },
        handleAjax: function(url, param, load, autoToastr, async_, type, timeout) {
            var self = this;
            if (load) var loadId = this.showLoading();
            return this.ajax(url, param, async_, type, timeout).then(function(resp) {
                if (self.debug && console) console.log(resp);
                if (load) self.closeLoading(loadId);
                if (resp.code === -4) {
                    self.login();
                } else if (resp.code === -2) {
                    layer.alert('管理员已经登录，无法再次登录', { closeBtn: 0 }, function(index) {
                        layer.close(index);
                    });
                } else if (resp.code !== -3 && resp.code !== -5) {
                    self.heartbeat();
                }
                return resp;
            }, function(err) {
                if (autoToastr) {
                    if (err.statusText == "timeout") {
                        toastr.error('网络超时，请求失败。');
                    } else {
                        toastr.error('系统错误，请联系管理员。');
                    }
                }
                if (load) self.closeLoading(loadId);
                return err.statusText;
            });
        },
        uploadFile: function(url, from, load, autoToastr, async_, timeout) {
            var self = this;
            if (load) var loadId = this.showLoading();
            return this.fileAjax(url, new FormData(from), async_, 'POST', timeout).then(function(resp) {
                if (self.debug && console) console.log(resp);
                if (load) self.closeLoading(loadId);
                if (resp.code === -4) {
                    self.login();
                } else if (resp.code !== -3 && resp.code !== -5) {
                    self.heartbeat();
                }
                return resp;
            }, function(err) {
                if (autoToastr) {
                    if (err.statusText == "timeout") {
                        toastr.error('网络超时，请求失败。');
                    } else {
                        toastr.error('系统错误，请联系管理员。');
                    }
                }
                if (load) self.closeLoading(loadId);
                return err.statusText;
            });
        },
        showLoading: function() {
            return layer.load(2, {
                shade: [0.5, '#fff'] // 0.5透明度的白色背景
            });
        },
        closeLoading: function(i) {
            layer.close(i);
        },
        login: function() {
            var self = this;
            require(['md5'], function(md5) {
                layer.prompt({ title: '未检测到登录用户，请输入密码登录。', formType: 1, btn: '确定', closeBtn: 0 }, function(pass, index) {
                    localStorage.loginUid = new Date().getTime() + '' + Math.random();
                    self.handleAjax('login', { login: '1', pass: md5(pass) }, true, false).done(function(result) {
                        if (result.login === true) {
                            window.location.reload();
                        } else if (result.login === false) {
                            layer.alert('密码错误，登录失败。');
                        } else if (result.login === '') {
                            layer.alert('系统错误，登录失败。');
                        }
                    }).fail(function(error) {
                        if (error == "timeout") {
                            layer.alert('网络超时，登录失败。');
                        } else {
                            layer.alert('系统错误，登录失败。');
                        }
                    });
                });
            });
        },
        loginOut: function() {
            if (!localStorage.loginUid) {
                clearInterval(heartbeatCount);
                this.login();
                return;
            }
            var self = this;
            layer.confirm('确定退出登录？', { btn: ['确认', '取消'] }, function(index) {
                self.handleAjax('login', { login: '2' }, true, false).done(function(result) {
                    if (result.login) {
                        layer.close(index);
                        localStorage.loginUid = '';
                        window.location.reload();
                    } else {
                        layer.alert('退出登录失败。');
                    }
                }).fail(function(error) {
                    if (error == "timeout") {
                        layer.alert('网络超时，退出登录失败。');
                    } else {
                        layer.alert('系统错误，退出登录失败。');
                    }
                });
            });
        },
        heartbeat: function() {
            var self = this;
            self.handleAjax('login', { login: '3' }, false, false, true, 'POST', 1000);
            clearInterval(heartbeatCount);
            heartbeatCount = setInterval(function() {
                self.handleAjax('login', { login: '3' }, false, false, true, 'POST', 1000);
            }, 60 * 1000);
        },
        formatStyle: function(val) {
            if (!val) return '';
            var tempList = val.split(';');
            val = '';
            for (var i = 0; i < tempList.length; i++) {
                var style = $.trim(tempList[i]).split(':');
                if (style.length !== 2) {
                    continue;
                } else {
                    val += $.trim(style[0]) + ': ' + $.trim(style[1]) + '; ';
                }
            }
            return val.substr(0, val.length - 1);
        }
    }

    return common;
});